package com.foreverwin.mes.lims.service.impl;

import com.foreverwin.mes.common.constants.HandleBOConstants;
import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.common.enums.IDUtils;
import com.foreverwin.mes.core.base.FrontPage;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.DateUtil;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.dto.InspectTaskDto;
import com.foreverwin.mes.lims.enums.InspectObject;
import com.foreverwin.mes.lims.enums.InspectType;
import com.foreverwin.mes.lims.mapper.InspectPlanDetailMapper;
import com.foreverwin.mes.lims.model.*;
import com.foreverwin.mes.lims.mapper.InspectTaskMapper;
import com.foreverwin.mes.lims.service.InspectPlanDetailService;
import com.foreverwin.mes.lims.service.InspectPlanService;
import com.foreverwin.mes.lims.service.InspectProjectService;
import com.foreverwin.mes.lims.service.InspectTaskService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.foreverwin.mes.lims.util.DataValueConstant;
import com.foreverwin.mes.lims.util.NowString;
import com.foreverwin.mes.lims.vo.InspectTaskVo;
import com.foreverwin.mes.meapi.dto.GenerateNextNumberRequest;
import com.foreverwin.mes.meapi.dto.GenerateNextNumberResponse;
import com.foreverwin.mes.meapi.model.*;
import com.foreverwin.mes.meapi.service.*;
import com.foreverwin.mes.so.model.ShopOrderDispatch;
import com.foreverwin.mes.so.model.ShopOrderDispatchDetail;
import com.foreverwin.mes.so.service.ShopOrderDispatchDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Levy
 * @since 2020-02-24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InspectTaskServiceImpl extends ServiceImpl<InspectTaskMapper, InspectTask> implements InspectTaskService {

    private static Logger logger = LoggerFactory.getLogger(InspectTaskServiceImpl.class);
    private static long Minute = 1000 * 60;// 一分钟的毫秒数
    private static long Hour = 1000 * 60 * 60;// 一小时的毫秒数
    private static long Day = 1000 * 24 * 60 * 60;// 一天的毫秒数


    @Autowired
    private InspectTaskMapper inspectTaskMapper;

    @Autowired
    private ResrceService resrceService;
    @Autowired
    private WorkCenterService workCenterService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private InspectPlanDetailMapper inspectPlanDetailMapper;
    @Autowired
    private OperationService operationService;
    @Autowired
    NextNumberService nextNumberService;
    @Autowired
    ShopOrderDispatchDetailService shopOrderDispatchDetailService;
    @Autowired
    InspectProjectService inspectProjectService;
    @Autowired
    InspectPlanService inspectPlanService;
    @Autowired
    CustomFieldsService customFieldsService;
    @Autowired
    SfcInWorkService sfcInWorkService;
    @Autowired
    InspectPlanDetailService inspectPlanDetailService;
    @Autowired
    UserCertService userCertService;
    @Autowired
    public InspectTaskService inspectTaskService;


    @Override
    public Page<InspectTask> selectPage(FrontPage<InspectTask> frontPage, InspectTask inspectTask) {
        EntityWrapper<InspectTask> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(inspectTask);
        return super.selectPage(frontPage.getPagePlus(), queryWrapper);
    }

    @Override
    public List<InspectTask> selectList(InspectTask inspectTask) {
        EntityWrapper<InspectTask> queryWrapper = new EntityWrapper<>();
        queryWrapper.setEntity(inspectTask);
        return super.selectList(queryWrapper);
    }

    @Override
    public void doSave(InspectTaskVo inspectTaskVo) {

        String object = inspectTaskVo.getObject();
        String site = inspectTaskVo.getSite();
        String resrceBo = inspectTaskVo.getResrce();
        String workCenterBo = inspectTaskVo.getWorkCenter();
        String operation = inspectTaskVo.getOperation();
        String checkType = inspectTaskVo.getCheckType();
        String item = inspectTaskVo.getItem();
        String itemDesc = inspectTaskVo.getItemDesc();
        String user = inspectTaskVo.getUser();
        String planBo;
        InspectTask inspectTask = new InspectTask();
        Date now = new Date();

        if ( InspectObject.RES.name().equals( object ) ){
            Resrce oldResrce =  resrceService.selectById( resrceBo );
            if ( oldResrce == null ){
                throw BusinessException.build("设备["+ HandleEnum.RESOURCE.getPart( resrceBo , 1 ) +"]不存在!");
            }
            List<Operation> operationList = operationService.listByResource( resrceBo );
            if(operationList.size() == 0) {
                throw BusinessException.build("设备【"  + oldResrce.getResrce() +"】没有找到对应的操作");
            }
            String workshopSection = operationList.get(0).getOperation();
            if ( !workshopSection.equals( operation ) ){
                throw BusinessException.build("操作【"+ operation +"】不是设备【"+ oldResrce.getResrce() + "】对应操作!");
            }

            planBo = HandleBOConstants.INSPECT_PLAN_BO + ":" + resrceBo;
        }else if ( InspectObject.PRO.name().equals( object ) ){
            if ( StringUtils.isBlank( item ) ){
                throw BusinessException.build( "物料编号不能为空！" );
            }
            Item item1 = itemService.selectItemByCode( site , item );
            if ( item1 == null ){
                throw BusinessException.build("物料["+ item +"]不存在");
            }
            List<Operation> operationList = operationService.listByResource( resrceBo );
            if(operationList.size() == 0) {
                throw BusinessException.build("设备【"  + HandleEnum.RESOURCE.getPart( resrceBo , 1 ) +"】没有找到对应的操作");
            }
            String workshopSection = operationList.get(0).getOperation();
            if ( !workshopSection.equals( operation ) ){
                throw BusinessException.build("操作【"+ operation +"】不是设备【"+ HandleEnum.RESOURCE.getPart(resrceBo,1) + "】对应操作!");
            }
            planBo = HandleBOConstants.INSPECT_PLAN_BO + ":" + item1.getItemGroupBo() ;
        }else if ( InspectObject.ENV.name().equals( object ) ){
            WorkCenter workCenter1 = workCenterService.selectById( workCenterBo );
            if ( workCenter1 == null ){
                throw BusinessException.build("工作中心["+ workCenterBo.split(",")[1] + "]不存在");
            }
            planBo = HandleBOConstants.INSPECT_PLAN_BO + ":" + workCenterBo;
        }else {
            throw BusinessException.build( "请选择正确对象!" );
        }

        //该类型检验计划是否存在
        Map paramMap = new HashMap();
        paramMap.put( "PLAN_BO",planBo );
        paramMap.put("INSPECT_TYPE", checkType );
        List<InspectPlanDetail> inspectPlanDetails =inspectPlanDetailMapper.selectByMap( paramMap );
        if ( inspectPlanDetails.isEmpty() ){
            throw BusinessException.build("请维护检验计划!");
        }
        InspectPlanDetail inspectPlanDetail = inspectPlanDetails.get( 0 );
        String isSample = inspectPlanDetail.getIsSample();
        //自动生成任务编号 INSPECT_TASK_NO
        GenerateNextNumberRequest request = new GenerateNextNumberRequest();
        request.setSite(site);
        request.setDateTime(new Date());
        request.setNextNumberType("INSPECT_TASK_NO");
        request.setNumberOfValues(1);
        GenerateNextNumberResponse response = nextNumberService.generateNextValues( request );
        List<String> ids =  response.getIds();
        String taskId = ids.get(0);

        inspectTask.setHandle( HandleBOConstants.INSPECT_TASK_BO+":"+ site + "," +UUID.randomUUID().toString() );
        inspectTask.setSite( site );
        inspectTask.setPlanBo( planBo );
        inspectTask.setObject( object );
        if ( "true".equals( isSample ) ){
            inspectTask.setTaskStatus( DataValueConstant.TASK_STATUS_NEW_WAIT ); //待取样
        }else {
            inspectTask.setTaskStatus( DataValueConstant.TASK_STATUS_NEW ); //新建
        }
        inspectTask.setTaskType( DataValueConstant.TASK_TYPE_MANUAL );  //手动
        inspectTask.setInspectType( checkType );
        inspectTask.setItem( item );
        inspectTask.setItemDesc( itemDesc );
        inspectTask.setCreatedDateTime( now );
        inspectTask.setCreatedUser( user );
        inspectTask.setTaskId( taskId );    //检验任务ID

        int count =  inspectTaskMapper.insert( inspectTask );
        if(count <=0 ){
            throw BusinessException.build("检验任务创建失败");
        }

    }

    @Override
    public List<InspectTaskDto> doSearch(String object, String workCenter, String resrce, String site ,String user) {
        List<InspectTask> inspectTasks = new ArrayList<>();
        List<InspectTaskDto> inspectTaskDtos = new ArrayList<>();
        String planBo;
        String userBo = StringUtils.genHandle( HandleBOConstants.USER_BO,site,user );

        if ( InspectObject.ENV.name().equals( object ) ){

          WorkCenter workCenterModel = workCenterService.selectById( StringUtils.genHandle( HandleBOConstants.WORK_CENTER_BO ,site , workCenter ) );
          if ( workCenterModel == null ){
              throw BusinessException.build("工作中心【"+ workCenter+"】不存在!");
          }
         planBo = HandleBOConstants.INSPECT_PLAN_BO +":"+workCenterModel.getHandle();

         inspectTasks = inspectTaskMapper.selectTaskByPlanBo( planBo , userBo );
        }else if ( InspectObject.RES.name().equals( object ) ){
            Resrce resrceModel = resrceService.selectById( StringUtils.genHandle( HandleBOConstants.RESOURCE_BO ,site , resrce ) );
            if ( resrceModel == null ){
                throw BusinessException.build("设备【"+ resrce+"】不存在!");
            }
            planBo = HandleBOConstants.INSPECT_PLAN_BO+":"+resrceModel.getHandle();

            //2020 Max 新增创建时间区间
            inspectTasks = inspectTaskMapper.selectList(
                    new EntityWrapper<InspectTask>().between("CREATED_DATE_TIME", NowString.minDate(),new Date())
                    .eq("PLAN_BO",planBo)
                    .and()
                    .notIn( "TASK_STATUS" , DataValueConstant.TASK_STATUS_DELETE ) );
            List<Sfc> SfcList = sfcInWorkService.selectSfc( resrceModel.getHandle() );

            if ( !SfcList.isEmpty() ){
                //查找设备在做物料对应的任务
                Sfc sfc = SfcList.get( 0 );
                Item item = itemService.selectById( sfc.getItemBo() );
                planBo =  HandleBOConstants.INSPECT_PLAN_BO+":"+item.getItemGroupBo();

                //2020 Max 新增创建时间区间
                inspectTasks.addAll(
                        inspectTaskMapper.selectList(
                                new EntityWrapper<InspectTask>().between("CREATED_DATE_TIME", NowString.minDate(),new Date())
                                        .eq("PLAN_BO",planBo)
                                        .and()
                                        .notIn( "TASK_STATUS" , DataValueConstant.TASK_STATUS_DELETE ) )
                ) ;
            }

        }else {
            throw BusinessException.build("任务对象错误");
        }
        //改检验类型中文描述
        if ( !inspectTasks.isEmpty() ){
            inspectTaskDtos =  chageInspectType( inspectTasks ,planBo );
        }

        return inspectTaskDtos;
    }

    private List<InspectTaskDto> chageInspectType(List<InspectTask> inspectTasks ,String planBo ){
        List<InspectTaskDto> inspectTaskDtos = new ArrayList<>();
        inspectTasks.forEach( inspectTask ->{
                    String type = inspectTask.getInspectType();
                    InspectTaskDto inspectTaskDto = new InspectTaskDto();
                    inspectTaskDto.setTaskId( inspectTask.getTaskId() );
                    inspectTaskDto.setInspectType( InspectType.valueOf( type ).getDescription() );
                    inspectTaskDto.setTaskStatus( inspectTask.getTaskStatus() );
                    inspectTaskDto.setCreatedDateTime( inspectTask.getCreatedDateTime() );
                    inspectTaskDto.setItem( inspectTask.getItem() );
                    inspectTaskDto.setItemDesc( inspectTask.getItemDesc() );
                    List<InspectPlanDetail> inspectPlanDetails = inspectPlanDetailMapper.selectList(
                            new EntityWrapper<InspectPlanDetail>()
                            .eq( "PLAN_BO",planBo )
                            .eq("INSPECT_TYPE",type));
                    if ( !inspectPlanDetails.isEmpty() ){
                        InspectPlanDetail inspectPlanDetail = inspectPlanDetails.get( 0 );
                        /*String project = inspectPlanDetail.getInspectProject();
                        if ( !StringUtils.isBlank( project ) ){
                            InspectProject inspectProject = inspectProjectService.selectOne(
                                    new EntityWrapper<InspectProject>()
                                            .eq("PROJECT_NO",project)
                                            .eq("CURRENT_REVISION","Y")
                            );
                            inspectTaskDto.setVersion( inspectProject == null ? "" : inspectProject.getRevision() );
                        }*/
                        inspectTaskDto.setVersion( inspectPlanDetail.getRevision() );
                    }
                    inspectTaskDtos.add( inspectTaskDto ); }
                );

        return  inspectTaskDtos;
    }

    @Override
    public void autoCreatedTask(List<InspectPlanDetail> inspectPlanDetails, String site, String user) {

        inspectPlanDetails.stream().forEach(inspectPlanDetail -> {
            Date now = new Date();
            String planBo = inspectPlanDetail.getPlanBo();
            String type = inspectPlanDetail.getInspectType();
            String time = inspectPlanDetail.getTime();
            String unit = inspectPlanDetail.getUnit();
            InspectTask prevInspectTask = null; //最近一笔任务
            String taskNo = getInspectTaskNextNumber( site );

            //增加筛选任务类型为"A"自动创建的条件 2020/4/15 Max
           List<InspectTask> inspectTasks = inspectTaskMapper.selectList(
                    new EntityWrapper<InspectTask>()
                    .eq("PLAN_BO", planBo )
                    .eq("INSPECT_TYPE" , type )
                    .eq("TASK_TYPE","A")
                   .orderDesc(Arrays.asList( "CREATED_DATE_TIME" ))
            );

           if ( !inspectTasks.isEmpty() ){
               prevInspectTask = inspectTasks.get( 0 );
           }

            InspectPlan inspectPlan = inspectPlanService.selectById( planBo );
            String resrceBo = inspectPlan.getResrce();
            if ( resrceBo != null && !"".equals(resrceBo) ) {
                Resrce resrce = resrceService.selectById(resrceBo);
                if (resrce == null) {
                    throw BusinessException.build("设备【" + HandleEnum.RESOURCE.getPart(resrceBo, 1) + "】不存在");
                }
            }

            String _resrce = resrceBo.split(",")[1];
            Resrce resrce = resrceService.selectByCode( inspectPlan.getSite(),_resrce);
            Map resrceMap =inspectTaskService.doSearchItemByResrce( resrce );
            String item = (String)resrceMap.get("item");
            String itemDesc = (String)resrceMap.get("itemDesc");
            InspectTask inspectTask =  new InspectTask();

            Long interval = 0L;
            switch ( unit ){
                case "D":
                    interval = Long.valueOf(time) * Day;
                    break;
                case "H":
                    interval = Long.valueOf(time) * Hour;
                    break;
                case "M":
                    interval = Long.valueOf(time) * Minute;
                    break;
                default:
                    break;
            }
            if (prevInspectTask == null) {
                //获取下一个任务的生成时间
                Date createTime = getNextInspactTaskCreateTime( null,inspectPlanDetail,interval);
                inspectTask.setHandle(HandleBOConstants.INSPECT_TASK_BO + ":" + site + "," + UUID.randomUUID().toString());
                inspectTask.setSite(site);
                inspectTask.setPlanBo(planBo);
                inspectTask.setObject(inspectPlan.getResrce());
                inspectTask.setTaskStatus(DataValueConstant.TASK_STATUS_NEW); //开始
                inspectTask.setTaskType(DataValueConstant.TASK_TYPE_AUTO);  //自动
                inspectTask.setInspectType(type);
                inspectTask.setItem( item );
                inspectTask.setItemDesc( itemDesc );
                inspectTask.setCreatedDateTime(createTime);
                inspectTask.setCreatedUser(user);
                inspectTask.setTaskId(taskNo);
            } else {
                if (DataValueConstant.TASK_STATUS_COMPLETE.equals(prevInspectTask.getTaskStatus())
                        || DataValueConstant.TASK_STATUS_DELETE.equals(prevInspectTask.getTaskStatus())) {

                    Date createTime = getNextInspactTaskCreateTime( null,inspectPlanDetail,interval);
                    //Date endTime = prevInspectTask.getEndTime();
                    if (createTime == null) {
                        logger.error("任务生成时间为空，无法产生新的任务");
                        return;
                    }
                        inspectTask.setHandle(HandleBOConstants.INSPECT_TASK_BO + ":" + site + "," + UUID.randomUUID().toString());
                        inspectTask.setSite(site);
                        inspectTask.setPlanBo(planBo);
                        inspectTask.setObject(inspectPlan.getResrce());
                        inspectTask.setTaskStatus(DataValueConstant.TASK_STATUS_NEW); //开始
                        inspectTask.setTaskType(DataValueConstant.TASK_TYPE_AUTO);  //自动
                        inspectTask.setInspectType(type);
                        inspectTask.setCreatedDateTime( createTime );
                        inspectTask.setCreatedUser(user);
                        inspectTask.setTaskId(taskNo);
                        inspectTask.setItem(item);
                        inspectTask.setItemDesc(itemDesc);

                }
            }
           /* String resrceStatusBo = resrce.getStatusBo();
            InspectTask inspectTask =  new InspectTask();
            long timeNum = 1l;
            //检查时间
            if ( !StringUtils.isBlank( time ) ){
                timeNum = timeNum * Long.parseLong( time );
            }else {

            }*/
           /* //检查设备状态
            if ( "DOWN".equals( HandleEnum.STATUS.getPart( resrceStatusBo , 1 ) ) ){
                if( prevInspectTask == null ){
                    inspectTask.setHandle( HandleBOConstants.INSPECT_TASK_BO+":"+ site + "," +UUID.randomUUID().toString() );
                    inspectTask.setSite( site );
                    inspectTask.setPlanBo( planBo );
                    inspectTask.setObject( inspectPlan.getResrce() );
                    inspectTask.setTaskStatus( DataValueConstant.TASK_STATUS_NEW ); //开始
                    inspectTask.setTaskType( DataValueConstant.TASK_TYPE_AUTO );  //自动
                    inspectTask.setInspectType( type );
                    inspectTask.setCreatedDateTime( now );
                    inspectTask.setCreatedUser( user );
                    inspectTask.setTaskId( taskNo );    //检验任务ID

                } else {
                    //前一个任务未完成不可生成下一个任务
                    if ( DataValueConstant.TASK_STATUS_COMPLETE.equals( prevInspectTask.getTaskStatus() ) ){
                        *//**
                         * 前一个任务的结束时间减去创建时间的差值，差值除计划的单位时间取整数倍，
                         * 整数倍乘单位时间加上前任务的创建时间即为下一个任务的创建时间。
                         *//*
                        long prevCreatedDate = prevInspectTask.getCreatedDateTime().getTime(); //上一个任务创建时间
                        long prevEndDate = prevInspectTask.getEndTime().getTime(); //上一个任务结束时间
                        long diffDate = prevEndDate - prevCreatedDate;
                        long unitTime = 1l;
                        switch ( unit ){
                            case "D":
                                unitTime = timeNum * Day;
                                break;
                            case "H":
                                unitTime = timeNum * Hour;
                                break;
                            case "M":
                                unitTime = timeNum * Minute;
                                break;
                        }
                       long divisor = ( diffDate / unitTime ) < 1l ?  1l : ( diffDate / unitTime ) ;
                       long nextCretedTime =   divisor * unitTime + prevCreatedDate ;
                       Date nextCreatedDate = new Date( nextCretedTime );

                        inspectTask.setHandle( HandleBOConstants.INSPECT_TASK_BO+":"+ site + "," +UUID.randomUUID().toString() );
                        inspectTask.setSite( site );
                        inspectTask.setPlanBo( planBo );
                        inspectTask.setObject( inspectPlan.getResrce() );
                        inspectTask.setTaskStatus( DataValueConstant.TASK_STATUS_NEW ); //开始
                        inspectTask.setTaskType( DataValueConstant.TASK_TYPE_AUTO );  //自动
                        inspectTask.setInspectType( type );
                        inspectTask.setCreatedDateTime( nextCreatedDate );
                        inspectTask.setCreatedUser( user );
                        inspectTask.setTaskId( taskNo );    //检验任务ID
                    }
                }
            }*/

            if ( !StringUtils.isBlank( inspectTask.getHandle() ) ){
                inspectTaskMapper.insert( inspectTask );
            }

        });


    }

    /**
     * 获取下一个任务的创建时间
     * @return
     * @author Max
     * @date 2020/04/14
     */
    private Date getNextInspactTaskCreateTime (InspectTask prevInspectTask,InspectPlanDetail inspectPlanDetail,Long interval) {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:SS" );
        Date nextCreateTime = null;
        if (prevInspectTask == null ) {
                String planBo = inspectPlanDetail.getPlanBo();
                InspectPlan inspectPlan = inspectPlanService.selectById(planBo);
                Date createTime = null;
                if ( inspectPlan != null ) {
                   createTime = inspectPlan.getUpdatedDateTime() == null ? inspectPlan.getCreatedDateTime() : inspectPlan.getUpdatedDateTime();
                } else {
                    logger.info( "检验类型{}对应的检验计划{}不存在，请确保检验计划", inspectPlanDetail.getHandle(),inspectPlanDetail.getPlanBo());
                    return null;
                }
                    //第一次创建任务时间处理
                    String ct = sdf.format( createTime );
                    String currentTime = sdf.format( new Date() );
                    String _ct=ct.substring( 0,11 );
                    currentTime =currentTime.substring( 0,11 );
                    if (! _ct.equals( currentTime )) {
                        //拼接成当日时间
                        ct =currentTime+ct.substring(11,19);
                        Date _createDate = null;
                        try {
                            _createDate = sdf.parse( ct );
                            Date _currentTime = new Date();
                            long dValue = _currentTime.getTime() - _createDate.getTime();
                            long cycleNum = dValue/interval;
                            createTime = _createDate;
                            return nextCreateTime= new Date(createTime.getTime() + (cycleNum+1)*interval);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
        } else {
                Date createTime = prevInspectTask.getCreatedDateTime();
                //使用绝对时间时间戳，可以保证结束时间必然大于创建时间
                Date endTime = prevInspectTask.getEndTime();
                if ( createTime != null && endTime != null ) {
                    /*long dValue = endTime.getTime() - createTime.getTime();
                    long cycleNum = dValue/interval;
                    if (cycleNum < 0) {
                        nextCreateTime = new Date( createTime.getTime() - ( - cycleNum )*interval );
                    } else {
                        nextCreateTime = new Date( createTime.getTime() + (cycleNum+1)*interval );
                    }*/
                    //计算出离任务结束时间最近的一个任务创建时间点
                    int i = 0;
                    for ( i=0; i<99999; i++) {
                        if ( endTime.getTime() <= createTime.getTime() + i* interval) {
                            break;
                        }
                    }
                    //如果当前时间大于下一个要创建的任务那么再进行计算
                    if ( new Date().getTime() > createTime.getTime() + i* interval) {
                        int j = 0;
                        for ( j =0; j<99999; j++) {
                            if (  new Date().getTime() <= createTime.getTime() + j * interval) {
                                break;
                            }
                        }
                        nextCreateTime = new Date(createTime.getTime() + j* interval);
                    } else {
                        nextCreateTime = new Date(createTime.getTime() + i* interval);
                    }
                    return nextCreateTime;
                }
        }
        return null;
    }

    /**
     * 获取下一个任务编号
     * @param site
     * @return
     */
    private String getInspectTaskNextNumber(String site ){

        //自动生成任务编号 INSPECT_TASK_NO
        GenerateNextNumberRequest request = new GenerateNextNumberRequest();
        request.setSite(site);
        request.setDateTime(new Date());
        request.setNextNumberType("INSPECT_TASK_NO");
        request.setNumberOfValues(1);
        GenerateNextNumberResponse response = nextNumberService.generateNextValues( request );
        List<String> ids =  response.getIds();

        return ids.get(0);
    }

    @Override
    public Map doSearchItemByResrce(Resrce resrce ) {

      Map resultMap = new HashMap();
      if ( !StringUtils.isBlank( resrce.getOperationBo()  )  ){
          resultMap.put( "operation" , HandleEnum.OPERATION.getPart( resrce.getOperationBo() , 1 ) );
      }else {
          resultMap.put( "operation" ,"" );
      }

      resultMap.put( "resrce" ,resrce.getResrce() );
      resultMap.put( "description" ,resrce.getDescription() );
      resultMap.put( "resrceBo" ,resrce.getHandle() );
      resultMap.put("item","");
      resultMap.put("itemDesc","");
      resultMap.put("itemBo","");
      List<Sfc> SfcList = sfcInWorkService.selectSfc( resrce.getHandle() );

        if ( !SfcList.isEmpty() ){
          Sfc sfc = SfcList.get( 0 );
          Item item = itemService.selectById( sfc.getItemBo() );

          resultMap.put( "item" , item.getItem() );
          resultMap.put("itemDesc",item.getDescription());
          resultMap.put("itemBo",sfc.getItemBo());
      }

      return  resultMap;

    }

    @Override
    public void autoCreatedOSTask(List<InspectPlanDetail> inspectPlanDetails, String site, String user) {
        for ( InspectPlanDetail inspectPlanDetail : inspectPlanDetails ){
            Date now = new Date();
            InspectPlan inspectPlan = inspectPlanService.selectById( inspectPlanDetail.getPlanBo() );
            //外教针对设备
            Resrce resrce = resrceService.selectById( inspectPlan.getResrce() );
            if ( resrce == null ){
                logger.error("InspectTaskService >> autoCreatedOSTask --> failed --> cause plan{} resrce not found", inspectPlanDetail.getPlanBo() );
                continue;
            }
            String resrceBo = resrce.getHandle();
            //查找上一个外教任务
            List<InspectTask> inspectTasks = inspectTaskMapper.selectList(
                    new EntityWrapper<InspectTask>()
                            .eq("PLAN_BO", inspectPlanDetail.getPlanBo() )
                            .eq("INSPECT_TYPE" , InspectType.OS.getCode() )
                            .orderAsc(Arrays.asList( "CREATED_DATE_TIME" ))
            );
            InspectTask prevTask = null;
            if ( !inspectTasks.isEmpty() ){
                prevTask = inspectTasks.get( 0 );
            }
            List<CustomFields> customFieldsList = customFieldsService.listByHandle( resrceBo );
            String calibrationCycle = "";  //外校周期
            String calibrationDate = "";   //校准日期
            String calibrationExpirationWarning = "";   //外校提前提醒时间
            String proCalibrationExpirationDate = "";  //外校准有效日期
            for (CustomFields customFields : customFieldsList) {
                switch (customFields.getAttribute()) {
                    case DataValueConstant.RES_CALIBRATION_CYCLE:
                        calibrationCycle = customFields.getValue();
                        break;
                    case DataValueConstant.RES_CALIBRATION_DATE:
                        calibrationDate = customFields.getValue();
                        break;
                    case DataValueConstant.RES_CALIBRATION_EXPIRATION_WARNING:
                        calibrationExpirationWarning = customFields.getValue();
                        break;
                    case DataValueConstant.RES_PRO_CALIBRATION_EXPIRATION_DATE:
                        proCalibrationExpirationDate = customFields.getValue();
                        break;
                    default:
                        break;
                }
            }
            InspectTask inspectTask = new InspectTask();
            String taskId = getInspectTaskNextNumber( site );
            //补充字段
            inspectTask.setTaskId( taskId );
            inspectTask.setTaskStatus( DataValueConstant.TASK_STATUS_NEW );
            inspectTask.setSite( site );
            inspectTask.setInspectType( InspectType.OS.getCode() );
            inspectTask.setHandle( HandleBOConstants.INSPECT_TASK_BO+":"+ site + "," +UUID.randomUUID().toString() );
            inspectTask.setCreatedUser( user );
            inspectTask.setTaskType( DataValueConstant.TASK_TYPE_AUTO );
            inspectTask.setObject( InspectObject.RES.name() );
            inspectTask.setPlanBo( inspectPlanDetail.getPlanBo() );

            if ( prevTask == null ){
                //创建第一笔外教任务
                inspectTask.setCreatedDateTime( now );

            }else {
                String status = inspectTask.getTaskStatus();
                if ( !DataValueConstant.TASK_STATUS_COMPLETE.equals( status ) ){
                    logger.info( "创建任务失败：前一个任务未完成!" );
                    continue;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    long effectDate = sdf.parse( proCalibrationExpirationDate ).getTime();
                    long warnDate =  Long.parseLong( calibrationExpirationWarning ) * Hour;
                    long created = effectDate - warnDate ;

                    Date createdDate = new Date( created );
                    inspectTask.setCreatedDateTime( createdDate );

                } catch (ParseException e) {
                    logger.error("校准日期转换失败:"+ e.getMessage());
                    continue;
                }

            }
            inspectTaskMapper.insert( inspectTask );
        }

    }
}